<template>
	<div class="wrapper">
		<!-- 顶部应用栏 -->
		<header class="mdc-top-app-bar">
			<div class="mdc-top-app-bar__row">
				<section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-start">
					<BackButton />
					<h1 class="mdc-top-app-bar__title">我的钱包</h1>
				</section>
			</div>
		</header>

		<!-- 钱包信息卡片 -->
		<div class="wallet-card">
			<div class="balance-section">
				<p class="balance-label">账户余额</p>
				<p class="balance-amount">¥{{ walletInfo.balance || '0.00' }}</p>
			</div>
			<div class="wallet-details">
				<div class="detail-item">
					<span class="detail-label">可用余额</span>
					<span class="detail-value">¥{{ availableBalance || '0.00' }}</span>
				</div>
				<div class="detail-item" v-if="walletInfo.isAllowedOverdraft">
					<span class="detail-label">透支额度</span>
					<span class="detail-value">¥{{ walletInfo.overdraftAmount || '0.00' }}</span>
				</div>
				<div class="detail-item" v-if="walletInfo.isAllowedOverdraft && parseFloat(walletInfo.currentOverdraftAmount || 0) > 0">
					<span class="detail-label">当前透支</span>
					<span class="detail-value overdraft">¥{{ walletInfo.currentOverdraftAmount || '0.00' }}</span>
				</div>
				<div class="detail-item" v-if="walletInfo.repayDeadline">
					<span class="detail-label">最晚还款日</span>
					<span class="detail-value">{{ walletInfo.repayDeadline }}</span>
				</div>
				<div class="detail-item" v-if="parseFloat(walletInfo.frozenAmount || 0) > 0">
					<span class="detail-label">冻结金额</span>
					<span class="detail-value">¥{{ walletInfo.frozenAmount || '0.00' }}</span>
				</div>
			</div>
		</div>

		<!-- 功能按钮 -->
		<div class="action-buttons">
			<button class="action-btn recharge-btn" @click="toRecharge">
				<i class="fa fa-plus-circle"></i>
				<span>充值</span>
			</button>
			<button class="action-btn withdraw-btn" @click="toWithdraw">
				<i class="fa fa-minus-circle"></i>
				<span>提现</span>
			</button>
			<button class="action-btn loan-btn" @click="toLoan">
				<i class="fa fa-credit-card"></i>
				<span>借贷</span>
			</button>
			<button class="action-btn transaction-btn" @click="toTransaction">
				<i class="fa fa-list"></i>
				<span>交易流水</span>
			</button>
		</div>

		<!-- 逾期提醒 -->
		<div class="overdue-alert" v-if="hasOverdueLoan">
			<div class="alert-content">
				<i class="material-icons">warning</i>
				<div class="alert-text">
					<p class="alert-title">逾期提醒</p>
					<p class="alert-desc">您有逾期贷款，请及时还款，避免产生更多费用</p>
				</div>
			</div>
			<button class="alert-btn" @click="toRepay">立即还款</button>
		</div>

		<!-- 快捷操作 -->
		<div class="quick-actions">
			<h3 class="section-title">快捷操作</h3>
			<div class="action-item" v-if="walletInfo.isAllowedOverdraft && parseFloat(walletInfo.currentOverdraftAmount || 0) > 0" @click="toRepay">
				<i class="fa fa-credit-card"></i>
				<span>还款</span>
			</div>
		</div>

		<!-- 底部菜单部分 -->
		<AppFooter></AppFooter>
	</div>
</template>

<script>
	import AppFooter from '../components/AppFooter.vue';
	import BackButton from '../components/BackButton.vue';
	export default {
		name: 'MyWallet',
		data() {
			return {
				walletInfo: {
					walletId: '',
					balance: '0.00',
					frozenAmount: '0.00',
					availableBalance: '0.00',
					isVIP: false,
					isAllowedOverdraft: false,
					overdraftAmount: '0.00',
					currentOverdraftAmount: '0.00',
					repayDeadline: null
				},
				user: null,
				loanInfo: {
					hasOverdue: false,
					overdueAmount: '0.00',
					overdueDays: 0
				}
			}
		},
		computed: {
			availableBalance() {
				// 直接使用DTO返回的availableBalance字段
				return this.walletInfo.availableBalance || '0.00';
			},
			hasOverdueLoan() {
				// 模拟逾期检查：如果有透支且超过一定金额，视为有逾期
				return this.loanInfo.hasOverdue || 
					(this.walletInfo.isAllowedOverdraft && 
					parseFloat(this.walletInfo.currentOverdraftAmount || 0) > 100);
			}
		},
		created() {
			let user = this.$getSessionStorage('user');
			if (user == null) {
				this.$router.push('/login');
				return;
			}
			this.user = user;
			this.loadWalletInfo();
			this.loadLoanInfo();
		},
		activated() {
			// 从其他页面返回时刷新钱包信息
			if (this.user) {
				// 延迟刷新，确保后端数据已更新（特别是从提现、充值等页面返回时）
				setTimeout(() => {
					this.loadWalletInfo();
				}, 500);
			}
		},
		watch: {
			'$route'(to, from) {
				// 从充值页面返回时刷新钱包信息
				if (from.name === 'RechargePayment' || from.name === 'WalletRecharge' || 
					from.name === 'WalletWithdraw' || from.name === 'WalletTransaction' ||
					from.name === 'WalletRepay' || from.name === 'WalletLoan' || 
					from.name === 'LoanPayment') {
					if (this.user) {
						// 延迟刷新，确保后端数据已更新
						setTimeout(() => {
							this.loadWalletInfo();
						}, 300);
					}
				}
			}
		},
		mounted() {
			// 监听钱包余额更新事件
			if (window.addEventListener) {
				window.addEventListener('wallet-balance-updated', this.handleBalanceUpdate);
			}
		},
		beforeUnmount() {
			// 移除事件监听
			if (window.removeEventListener) {
				window.removeEventListener('wallet-balance-updated', this.handleBalanceUpdate);
			}
		},
		methods: {
			loadWalletInfo() {
				if (!this.user || !this.user.userId) {
					return;
				}
				
				this.$axios.post('wallet/info', this.$qs.stringify({
					walletId: this.user.userId
				})).then(response => {
					if (response.data && (response.data.code === 200 || response.data.code === '200')) {
						const result = response.data.result || {};
						// 确保所有字段都有默认值
						this.walletInfo = {
							walletId: result.walletId || this.user.userId,
							balance: result.balance || '0.00',
							frozenAmount: result.frozenAmount || '0.00',
							availableBalance: result.availableBalance || '0.00',
							isVIP: result.isVIP || false,
							isAllowedOverdraft: result.isAllowedOverdraft || false,
							overdraftAmount: result.overdraftAmount || '0.00',
							currentOverdraftAmount: result.currentOverdraftAmount || '0.00',
							repayDeadline: result.repayDeadline || null
						};
					} else {
						const errorMsg = response.data?.message || '获取钱包信息失败';
						console.error('获取钱包信息失败:', errorMsg);
						this.$toast?.error(errorMsg);
						// 重置为默认值
						this.walletInfo = {
							walletId: this.user.userId,
							balance: '0.00',
							frozenAmount: '0.00',
							availableBalance: '0.00',
							isVIP: false,
							isAllowedOverdraft: false,
							overdraftAmount: '0.00',
							currentOverdraftAmount: '0.00',
							repayDeadline: null
						};
					}
				}).catch(error => {
					console.error('获取钱包信息失败:', error);
					const errorMsg = error.response?.data?.message || error.message || '获取钱包信息失败';
					this.$toast?.error(errorMsg);
					// 重置为默认值
					this.walletInfo = {
						walletId: this.user.userId,
						balance: '0.00',
						frozenAmount: '0.00',
						availableBalance: '0.00',
						isVIP: false,
						isAllowedOverdraft: false,
						overdraftAmount: '0.00',
						currentOverdraftAmount: '0.00',
						repayDeadline: null
					};
				});
			},
			handleBalanceUpdate() {
				console.log('MyWallet收到钱包余额更新事件');
				// 延迟一点刷新，确保后端数据已更新
				setTimeout(() => {
					this.loadWalletInfo();
				}, 500);
			},
			toRecharge() {
				this.$router.push('/walletRecharge');
			},
			toWithdraw() {
				this.$router.push('/walletWithdraw');
			},
			toTransaction() {
				this.$router.push('/walletTransaction');
			},
			toRepay() {
				this.$router.push('/walletRepay');
			},
			toLoan() {
				this.$router.push('/walletLoan');
			},
			loadLoanInfo() {
				// 模拟加载贷款信息，检查是否有逾期
				// 实际应该从后端获取
				if (this.walletInfo.isAllowedOverdraft && parseFloat(this.walletInfo.currentOverdraftAmount || 0) > 0) {
					// 模拟逾期检查：透支超过100元且可用余额为负，视为逾期
					const overdraft = parseFloat(this.walletInfo.currentOverdraftAmount || 0);
					const available = parseFloat(this.walletInfo.availableBalance || 0);
					
					if (overdraft > 100 && available < 0) {
						this.loanInfo = {
							hasOverdue: true,
							overdueAmount: overdraft.toFixed(2),
							overdueDays: Math.floor(overdraft / 100) // 模拟逾期天数
						};
					}
				}
			}
		},
		components: {
			AppFooter,
			BackButton
		}
	}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 顶部应用栏 */
	.mdc-top-app-bar {
		background-color: #1976D2;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}

	.mdc-top-app-bar__row {
		display: flex;
		align-items: center;
		height: 72px;
		padding: 0 20px;
	}

	.mdc-top-app-bar__section {
		display: flex;
		align-items: center;
		gap: 16px;
		flex-direction: row;
	}

	.mdc-top-app-bar__title {
		font-size: 22px;
		font-weight: 500;
		margin: 0;
		white-space: nowrap;
		line-height: 1;
	}

	/****************** 钱包信息卡片 ******************/
	.wallet-card {
		margin-top: 0;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 0 0 20px 20px;
		padding: 8vw 6vw;
		color: #fff;
		box-shadow: 0 4px 12px rgba(0,0,0,0.1);
	}

	.balance-section {
		text-align: center;
		margin-bottom: 6vw;
	}

	.balance-label {
		font-size: 3.5vw;
		opacity: 0.9;
		margin-bottom: 2vw;
	}

	.balance-amount {
		font-size: 10vw;
		font-weight: bold;
		margin: 0;
	}

	.wallet-details {
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 12px;
		padding: 4vw;
	}

	.detail-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 2.5vw 0;
		border-bottom: 1px solid rgba(255, 255, 255, 0.2);
	}

	.detail-item:last-child {
		border-bottom: none;
	}

	.detail-label {
		font-size: 3.5vw;
		opacity: 0.9;
	}

	.detail-value {
		font-size: 4vw;
		font-weight: 500;
	}

	.detail-value.overdraft {
		color: #ffd700;
	}

	/****************** 功能按钮 ******************/
	.action-buttons {
		display: flex;
		justify-content: space-around;
		padding: 6vw 4vw;
		gap: 3vw;
	}

	.action-btn {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 4vw;
		border: none;
		border-radius: 12px;
		font-size: 3.5vw;
		cursor: pointer;
		transition: all 0.3s;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.action-btn i {
		font-size: 6vw;
		margin-bottom: 2vw;
	}

	.recharge-btn {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: #fff;
	}

	.withdraw-btn {
		background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
		color: #fff;
	}

	.transaction-btn {
		background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
		color: #fff;
	}

	.loan-btn {
		background: linear-gradient(135deg, #FF9800 0%, #FF5722 100%);
		color: #fff;
	}

	.action-btn:active {
		transform: scale(0.95);
	}

	/****************** 逾期提醒 ******************/
	.overdue-alert {
		background: linear-gradient(135deg, #f44336 0%, #e91e63 100%);
		margin: 4vw;
		border-radius: 12px;
		padding: 4vw;
		color: #fff;
		box-shadow: 0 4px 12px rgba(244, 67, 54, 0.3);
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 3vw;
	}

	.alert-content {
		display: flex;
		align-items: center;
		gap: 3vw;
		flex: 1;
	}

	.alert-content .material-icons {
		font-size: 6vw;
		opacity: 0.9;
	}

	.alert-text {
		flex: 1;
	}

	.alert-title {
		font-size: 4vw;
		font-weight: 600;
		margin: 0 0 1vw 0;
	}

	.alert-desc {
		font-size: 3.2vw;
		opacity: 0.9;
		margin: 0;
		line-height: 1.4;
	}

	.alert-btn {
		background-color: rgba(255, 255, 255, 0.3);
		border: 1px solid rgba(255, 255, 255, 0.5);
		color: #fff;
		padding: 2.5vw 4vw;
		border-radius: 8px;
		font-size: 3.5vw;
		cursor: pointer;
		transition: all 0.3s;
		white-space: nowrap;
	}

	.alert-btn:active {
		background-color: rgba(255, 255, 255, 0.4);
	}

	/****************** 快捷操作 ******************/
	.quick-actions {
		background-color: #fff;
		margin: 4vw;
		border-radius: 12px;
		padding: 4vw;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.section-title {
		font-size: 4vw;
		color: #666;
		margin: 0 0 3vw 0;
		font-weight: 500;
	}

	.action-item {
		display: flex;
		align-items: center;
		padding: 3vw;
		cursor: pointer;
		border-radius: 8px;
		transition: background-color 0.3s;
	}

	.action-item:hover {
		background-color: #f5f5f5;
	}

	.action-item i {
		font-size: 5vw;
		color: #0097FF;
		margin-right: 3vw;
	}

	.action-item span {
		font-size: 4vw;
		color: #333;
	}
</style>

